# -*- coding: utf-8 -*-
'''
Aftenposten TV plugin for XBMC
Copyright (C) 2011 olejl77@gmail.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''

import urllib
import re
import xbmc
import xbmcgui
import xbmcaddon
import xbmcplugin
from BeautifulSoup import BeautifulSoup
from Item import Item

__settings__ = xbmcaddon.Addon(id="plugin.video.no.aftenposten")
__language__ = __settings__.getLocalizedString

#categories: 
#xml-file: 



def createMainMenu(baseUrl, handle):
	"""
	Reads channels from aftenposten.no. When done sends them to Xbmc
	This is the plugin main menu
	"""
	soup = BeautifulSoup(urllib.urlopen('http://www.aftenposten.no/mm/video/V3/sections.xml'))
	channels = soup.findAll('section')

	listing = []
	for channel in channels:
		title = channel.sectiontitle.contents[0]
		url = channel.sectionrss.contents[0]
		cat_id = url[url.find('=',url.find('=') + 1) + 1 : url.find('&',url.find('&') + 1)]
		listing.append(Item(title=title, url=baseUrl+"?sub=" + str(cat_id)))		
	sendToXbmc(handle, listing)

def createSubMenu(baseUrl, handle, cat_id):
	url ='http://www.aftenposten.no/?service=rss2_video_list_sec_V1&uniquename=%s&video_antall=%s' % (cat_id, __settings__.getSetting("num"))
	soup = BeautifulSoup(urllib.urlopen(url))
	programs = soup.findAll('item')

	listing = []
	for program in programs:
		title = program.title.contents[0]
		description = program.description.contents[0]
		guid = program.guid.contents[0]
		pubdate = program.pubdate.contents[0]
		enclosure_url = program.enclosure['url']
		video_id = guid[guid.find('article') + 7 : guid.find('.ece')]

		tmp_url = 'http://www.aftenposten.no/template/mm/videourl.jsp?id=%s' % (video_id)
		tmp_soup = BeautifulSoup(urllib.urlopen(tmp_url))
		tmp_url = tmp_soup.url.contents[0]
		tmp_soup = BeautifulSoup(urllib.urlopen(tmp_url))
		imgpath = tmp_soup.imgpath.contents[0]
		videourl = tmp_soup.videodirectory.contents[0] + tmp_soup.videofile.contents[0]

		listing.append(Item(progid=video_id, title=title, date=pubdate,
			url=videourl, thumb=imgpath, isPlayable=True))

	sendToXbmc(handle, listing)

def sendToXbmc(handle, listing):
	"""
	Sends a listing to XBMC for display as a directory listing
	Plugins always result in a listing
	@param list listing
	@retur n void
	"""
	# send each item to xbmc
	for item in listing:
		listItem = xbmcgui.ListItem(item.title, thumbnailImage=item.thumb)
		listItem.setInfo(type="Video", infoLabels={"title": item.title, "plot":item.description,
		"duration":item.duration, "rating":int(item.rating), "playcount":int(item.viewed),
		"date":item.date, "votes":item.votes})
		xbmcplugin.addDirectoryItem(handle, item.url, listItem, not item.isPlayable)

	# tell xbmc we have finished creating the directory listing
	xbmcplugin.endOfDirectory(handle)

if ( __name__ == "__main__" ):
	xbmcplugin.setContent(int(sys.argv[1]), "episodes")
	xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
	xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)

	arg = sys.argv[2].split('=')

	if (arg[0] == "?sub"):
		createSubMenu(sys.argv[0], int(sys.argv[1]), arg[1])
	else:
		createMainMenu(sys.argv[0], int(sys.argv[1]))

